import { CopyOutlined, LeftOutlined, QrcodeOutlined } from '@ant-design/icons'
import { Button, Input, InputRef, message, Popover, Space, Tooltip, Typography } from 'antd'
import React, { useMemo, useRef } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import useGetPageInfo from '../../../hooks/useGetPageInfo'
import QRCode from 'qrcode.react'

import styles from './StatHeader.module.scss'

const StatHeader: React.FC = () => {
  const nav = useNavigate()
  const { title, isPublished } = useGetPageInfo()
  const { id } = useParams()
  const urlInputRef = useRef<InputRef>(null)

  /* function genLinkAndQRCodeElem() {
    if (!isPublished) return null

    const url = `http://localhost:3000/question/${id}` // 需要参考 C 端的 url

    const QRCodeElem = (
      <div style={{ textAlign: 'center' }}>
        <QRCode value={url} size={150} />
      </div>
    )
    return (
      <Space>
        <Input value={url} style={{ width: '300px' }} ref={urlInputRef} />
        <Tooltip title="拷贝链接">
          <Button icon={<CopyOutlined />} onClick={copyLink}></Button>
        </Tooltip>
        <Popover content={QRCodeElem}>
          <Button icon={<QrcodeOutlined />}></Button>
        </Popover>
      </Space>
    )
  } */

  // 拷贝链接
  function copyLink() {
    // 拷贝
    const elem = urlInputRef.current

    if (!elem) return
    elem.select() // 选择 input 的内容
    document.execCommand('copy') // 拷贝选中内容
    message.success('拷贝成功!')
  }

  // useMemo 优化生成二维码的 tsx; 1. 依赖项是否经常变化; 2. 缓存的元素创建成本是否较高
  const LinkAnQRcodeElem = useMemo(() => {
    if (!isPublished) return null

    const url = `http://localhost:3000/question/${id}` // 需要参考 C 端的 url

    const QRCodeElem = (
      <div style={{ textAlign: 'center' }}>
        <QRCode value={url} size={150} />
      </div>
    )

    return (
      <Space>
        <Input value={url} style={{ width: '300px' }} ref={urlInputRef} />
        <Tooltip title="拷贝链接">
          <Button icon={<CopyOutlined />} onClick={copyLink}></Button>
        </Tooltip>
        <Popover content={QRCodeElem}>
          <Button icon={<QrcodeOutlined />}></Button>
        </Popover>
      </Space>
    )
  }, [id, isPublished])

  return (
    <div className={styles['header-wrapper']}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
              返回
            </Button>
            <Typography.Title>{title}</Typography.Title>
          </Space>
        </div>
        <div className={styles.main}>{LinkAnQRcodeElem}</div>
        <div className={styles.right}>
          <Button
            type="primary"
            onClick={() => {
              nav({ pathname: `/question/edit/${id}` })
            }}
          >
            编辑问卷
          </Button>
        </div>
      </div>
    </div>
  )
}

export default StatHeader
